<?php
class Post extends AppModel {

    public $recursive = -1;
    public $name = 'Post';
    public $validate = array('title' => array('notempty'));
    public $actsAs = array(
        'Clickable',
        'Archivable',
        'Trackable',
        'Searchable' => array(
            'fields' => array(
                'title', 'content',
                'post_term_id' => 'PostTerm.name'
            ),
            'name' => 'title'
        ),
        'Switchable' => array(
            'fileds' => array('published', 'commentable')
        ),
        'Tagging.Taggable'
    );

    // The Associations below have been created with all possible keys,
    // Those that are not needed can be removed
    public $belongsTo = array(
        'PostTerm' => array(
            'className' => 'PostTerm',
            'foreignKey' => 'post_term_id',
            'counterCache' => true
        )
    );

    public $hasMany = array(
        'Attachment' => array(
            'className' => 'Media.Attachment',
            'foreignKey' => 'foreign_key',
            'conditions' => array('Attachment.model' => 'Post'),
            'dependent' => true
        ),
        'Comment' => array(
            'className' => 'Comment',
            'foreignKey' => 'post_id',
            'dependent' => true,
            'conditions' => array('Comment.approved' => '1'),
            'fields' => '',
            'order' => '',
            'limit' => '',
            'offset' => '',
            'exclusive' => '',
            'finderQuery' => '',
            'counterQuery' => ''
        )
    );

    /* We have to mannualy update the attachment count in Posts table */
    public function afterSave($created){
        if(!$created){

            $this->query("UPDATE posts SET attachment_count=(SELECT COUNT(id) FROM attachments WHERE foreign_key={$this->id} AND model='Post') WHERE id={$this->id}");
        }

        return $this->id;
    }
    /* Get attachment for download */

    
public function getAttachment($id=null){
        if(!$id){
            return false;
        }
        $this->Attachment->recursive = -1;
        return $this->Attachment->read(null, $id);
    }
    /* Get post to view, special for comments */
    public function getViewedPost($id=null){
        if(!$id) return false;
        $post = $this->find('first', array(
            'conditions'=>array('Post.id'=>$id),
            'contain' =>array(
                'CreatedUser',
                'PostTerm',
                'Attachment',
                'Comment'=>array(
                    'order' => 'Comment.created ASC',
                    'User' => array('fields' => array('id', 'username', 'nickname'))
                )
            )
        ));
        return $post;
    }
}
?>